package cn.ipenta.auth.service;

import cn.ipenta.auth.entity.TokenModel;
import cn.ipenta.auth.entity.User;
import cn.ipenta.auth.manager.TokenManager;
import cn.ipenta.auth.repository.UserRepository;
import cn.ipenta.config.ResultStatus;
import cn.ipenta.config.ResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author ipenta
 * @ClassName: AuthService
 * @Description: TODO
 * @date 2017-09-27 下午1:12
 */
@Service
public class AuthService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private TokenManager tokenManager;


	public Map<String, Object> signin(String username, String password) {
		User user = userRepository.findByUsername(username);
		if (null == user ||  //未注册
				!user.getPassword().equals(password)) {  //密码错误
			//提示用户名或密码错误
			return ResultMapper.fail(ResultStatus.USERNAME_OR_PASSWORD_ERROR);
		}
		//生成一个token，保存用户登录状态
		TokenModel model = tokenManager.createToken(user.getId());
		return ResultMapper.success(model);
	}

	public Map<String, Object> signup(String username, String password) {
		User user = userRepository.findByUsername(username);
		if (null != user) {
			//提示用户名占用
			return ResultMapper.fail(ResultStatus.USERNAME_REGISTERED);
		}
		User userd = userRepository.save(new User(username,password));
		//生成一个token，保存用户登录状态
		if (null == userd){
			return ResultMapper.fail(ResultStatus.USER_REGISTER_FAIL);
		}
		TokenModel model = tokenManager.createToken(userd.getId());
		return ResultMapper.success(model);
	}


	public void signout(String email) {
	}
}
